﻿using Api;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Services;

/// <summary>
/// 小程序接口
/// </summary>
[ApiDescriptionSettings("小程序")]
public class AppletServices : BaseServices
{
    private readonly ISqlSugarClient db;

    private readonly WechatAppletApi wechat;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="db"></param>
    /// <param name="ali"></param>
    /// <param name="wechat"></param>
    /// <param name="douyin"></param>
    public AppletServices(ISqlSugarClient db, WechatAppletApi wechat)
    {
        this.db = db;
        this.wechat = wechat;
    }

    /// <summary>
    /// 小程序登录
    /// </summary>
    /// <param name="code"></param>
    /// <param name="pid"></param>
    /// <returns></returns>
    public async Task<object> Login(string code, int pid)
    {

        var (openid, access_token, unionid) = await wechat.Login(code);

        var user = await db.Queryable<Entity.Client>().Where(x => x.OpenId == openid).FirstAsync();

        if (user == null)
        {
            user = new Entity.Client
            {
                OpenId = openid,

                Unionid = unionid,

                Pid = pid
            };

            user.Id = await db.Insertable(user).ExecuteReturnIdentityAsync();
        }

        var token = JWTEncryption.Encrypt(new Dictionary<string, object>
        {
            { "UserId", user.Id },

            { "Role", Enums.TokenRole.客户 }
        });

        return Ok(new { token });
    }

    /// <summary>
    /// 获取二维码
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    [Authorize]
    public async Task<object> QrCode(Dto.CreateWechatQrCodeDto e)
    {
        if (e.scene == null || e.page == null) return No("缺少参数");

        var env = App.Configuration.GetSection("applet:wechat:env").Value ?? "";

        //release正式版 develop开发版
        var data = await wechat.CreatedQrCode(e.scene, e.page, env);

        return Ok(data);
    }

    

}
